package com.atguigu.tingshu.album.task;

import cn.hutool.core.collection.CollectionUtil;
import com.atguigu.tingshu.album.mapper.AlbumInfoMapper;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.tencentcloudapi.trtc.v20190722.TrtcClient;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;

/**
 * @author: atguigu
 * @create: 2024-08-17 14:10
 */
@Slf4j
@Component
public class RebuildBloomFilter {

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private AlbumInfoMapper albumInfoMapper;


    /**
     * 定时任务，重建布隆过滤器，将现有审核通过且未删除专辑ID新增到布隆过滤器
     */
    @Scheduled(cron = "0 0 2 1 * ?")
    //@Scheduled(cron = "0/5 * * * * ?")
    public void rebuildBloomFilter() {
        //1.获取原有布隆过滤器对象 获取原有布隆过滤器配置信息：期望数据规模，误判率，现有数据量
        RBloomFilter<Long> oldBloomFilter = redissonClient.getBloomFilter(RedisConstant.ALBUM_BLOOM_FILTER);
        long expectedInsertions = oldBloomFilter.getExpectedInsertions();
        double falseProbability = oldBloomFilter.getFalseProbability();
        long count = oldBloomFilter.count();
        //2.判断是否需要进行扩容 条件：实际数据量大于期望数据规模
        if (count >= expectedInsertions) {
            //3.新建布隆过滤器，完成初始化完成后，将现有有效数据存入布隆过滤器
            RBloomFilter<Long> newBloomFilter = redissonClient.getBloomFilter(RedisConstant.ALBUM_BLOOM_FILTER + "new");
            newBloomFilter.tryInit(expectedInsertions * 2, falseProbability);
            this.addDataToBloomFilter(newBloomFilter);
            //4.删除原有布隆过滤器 删除原有布隆过滤器配置 跟 位图数据
            oldBloomFilter.delete();
            //5.将新的布隆过滤器改名
            newBloomFilter.rename(RedisConstant.ALBUM_BLOOM_FILTER);
            return;
        }
        oldBloomFilter.delete();
        oldBloomFilter.tryInit(expectedInsertions, falseProbability);
        this.addDataToBloomFilter(oldBloomFilter);
    }


    private void addDataToBloomFilter(RBloomFilter<Long> bloomFilter) {
        //3.1 查询数据库中现有有效专辑ID
        LambdaQueryWrapper<AlbumInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AlbumInfo::getStatus, SystemConstant.ALBUM_STATUS_PASS);
        queryWrapper.select(AlbumInfo::getId);
        List<AlbumInfo> albumInfoList = albumInfoMapper.selectList(queryWrapper);
        if (CollectionUtil.isNotEmpty(albumInfoList)) {
            //3.2 循环加入到新布隆过滤器
            for (AlbumInfo albumInfo : albumInfoList) {
                bloomFilter.add(albumInfo.getId());
            }
        }

    }

}
